package com.punch.course.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.punch.common.enums.course.ClassStatusEnum;
import com.punch.common.enums.course.GradeEnum;
import com.punch.common.exception.BusinessException;
import com.punch.common.feign.FeignOrderService;
import com.punch.common.feign.FeignStudentService;
import com.punch.common.page.PageInfo;
import com.punch.common.redis.utils.UserUtil;
import com.punch.common.tools.BasePage;
import com.punch.common.utils.ImageUtil;
import com.punch.common.vo.course.classes.AppCourseClassPageVO;
import com.punch.common.vo.course.classes.AppCourseClassVO;
import com.punch.common.vo.course.classes.AppGoodsVO;
import com.punch.common.vo.course.classes.FeignClassVO;
import com.punch.common.vo.user.student.StudentVO;
import com.punch.course.exception.CourseExceptionEnum;
import com.punch.course.mapper.CourseClassMapper;
import com.punch.course.model.CourseClass;
import com.punch.course.model.CourseClassGoods;
import com.punch.course.model.CourseImage;
import com.punch.course.model.CourseSchool;
import com.punch.course.query.AppClassQueryInfo;
import com.punch.course.service.AppClassService;
import com.punch.course.service.CourseClassGoodsService;
import com.punch.course.service.CourseImageService;
import com.punch.course.service.CourseSchoolService;
import com.punch.course.util.CourseClassUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @className: AppClassServiceImpl
 * @description: App课程班级实现层
 * @author: wujj
 * @date: 2020/12/07 15:16
 **/
@Service
public class AppClassServiceImpl implements AppClassService {


    @Resource
    private CourseClassMapper courseClassMapper;

    @Resource
    private CourseSchoolService courseSchoolService;

    @Resource
    private FeignStudentService feignStudentService;

    @Resource
    private CourseClassGoodsService courseClassGoodsService;

    @Resource
    private CourseImageService courseImageService;

    @Resource
    private FeignOrderService feignOrderService;

    /**
     * app学生可选课程列表,查询该学生所在学校下的该学生年级的报名中的课程
     *
     * @param studentId 学生id
     * @param queryInfo 查询条件
     * @return PageInfo<AppCourseClassPageVO>
     */
    @Override
    public PageInfo<AppCourseClassPageVO> listCourseClass(Long studentId, AppClassQueryInfo queryInfo) {
        if (studentId == null || studentId == 0L) {
            return new PageInfo<>();
        }
        //查找该学生的学校id
        StudentVO student = feignStudentService.getFeignStudentById(UserUtil.getLoginUserId(), studentId);
        if (student == null || student.getStudentId() == null) {
            return new PageInfo<>();
        }
        //查找该学生的订单
        AppClassQueryInfo appClassQueryInfo = new AppClassQueryInfo();
        appClassQueryInfo.setSchoolId(student.getSchoolId());
        appClassQueryInfo.setGradeYear(student.getGradeYear());
        appClassQueryInfo.setClassStatus(ClassStatusEnum.SIGN_IN.getCode());
        return BasePage.queryBasePage(appClassQueryInfo, params -> courseClassMapper.queryAppCount(params),
                params -> {
                    List<AppCourseClassPageVO> retList = courseClassMapper.queryAppList(params);
                    retList.forEach(p -> {
                        p.setCourseImg(ImageUtil.addPrefix(p.getCourseImg()));
                        int courseHourAmount = (p.getCourseHourPrice() * p.getCourseHourCount()) + p.getGoodsAmount();
                        p.setCourseHourAmount(courseHourAmount);
                    });
                    return retList;
                });
    }

    /**
     * 班级课程详情
     *
     * @param courseClassId 班级课程id
     * @param studentId     学生id
     * @return AppCourseClassVO
     */
    @Override
    public AppCourseClassVO getCourseClassForApp(Long courseClassId, Long studentId) {
        AppCourseClassVO appCourseClassVO = courseClassMapper.selectAppCourseClass(courseClassId);
        Optional.ofNullable(appCourseClassVO).orElseThrow(() -> new BusinessException(CourseExceptionEnum.CLASS_DETAIL_FAIL_NULL));
        appCourseClassVO.setCourseTime(CourseClassUtil.getIntWeekToString(appCourseClassVO.getCourseWeek(), appCourseClassVO.getClassTime()));
        appCourseClassVO.setAddress(appCourseClassVO.getSchoolName() + " " + appCourseClassVO.getClassRoomName());
        appCourseClassVO.setCourseImg(ImageUtil.addPrefix(appCourseClassVO.getCourseImg()));
        appCourseClassVO.setCourseHourAmount(appCourseClassVO.getCourseHourCount() * appCourseClassVO.getCourseHourPrice());
        if (appCourseClassVO.getGoodsFlag() == 1) {
            //查找教材教具信息
            AppGoodsVO goodMaterial = getGoodMaterial(courseClassId);
            appCourseClassVO.setMaterial(goodMaterial);
        }
        //获取图片
        List<String> introduceImg = getIntroduceImg(appCourseClassVO.getCourseId());
        appCourseClassVO.setIntroduceImagList(introduceImg);
        //学生id不为0,查找学生对该课程状态
        if (studentId != 0L) {
            setBtnStatus(courseClassId, studentId, appCourseClassVO);
        } else {
            appCourseClassVO.setClassStatus(null);
        }
        return appCourseClassVO;
    }


    /**
     * 服务间调用查询班级详情
     *
     * @param courseClassId 班级记录id
     * @return FeignClassVO
     * @author wujj
     * @since 2020/7/14 10:51
     */
    @Override
    public FeignClassVO getFeignClassById(Long courseClassId) {
        CourseClass courseClassEX = courseClassMapper.selectById(courseClassId);
        if (courseClassEX.getSignUpNumber().equals(courseClassEX.getStuNoMax())) {
            throw new BusinessException(CourseExceptionEnum.SIGN_UP_EXCEED_MAX);
        }
        Optional.ofNullable(courseClassEX).orElseThrow(() -> new BusinessException(CourseExceptionEnum.CLASS_DETAIL_FAIL_NULL));
        FeignClassVO feignClassVO = new FeignClassVO();
        feignClassVO.setCourseClassId(courseClassId);
        feignClassVO.setCourseClassName(courseClassEX.getClassName());
        feignClassVO.setType(courseClassEX.getType());
        Long courseId = courseClassEX.getCourseId();
        feignClassVO.setCourseId(courseId);
        feignClassVO.setCourseCreateId(courseClassEX.getCreateId());
        feignClassVO.setCourseCreateName(courseClassEX.getCreateName());
        feignClassVO.setClassOpenDate(courseClassEX.getActualOpenDate());
        feignClassVO.setTeacherName(courseClassEX.getTeacherName());
        feignClassVO.setClassRoomName(courseClassEX.getClassRoomName());
        feignClassVO.setClassTime(courseClassEX.getClassTime());
        CourseSchool courseSchoolEX = courseSchoolService.getById(courseId);
        Optional.ofNullable(courseSchoolEX).orElseThrow(() -> new BusinessException(CourseExceptionEnum.CLASS_DETAIL_FAIL_NULL));
        //课程信息
        feignClassVO.setCourseName(courseSchoolEX.getCourseName());
        feignClassVO.setCourseImg(courseSchoolEX.getCourseImg());
        feignClassVO.setCourseHourCount(courseSchoolEX.getCourseHourCount());
        feignClassVO.setCourseHourPrice(courseSchoolEX.getCourseHourPrice());
        feignClassVO.setCourseWeek(courseSchoolEX.getCourseWeek());
        feignClassVO.setBuyFlag(courseSchoolEX.getBuyFlag());
        feignClassVO.setCourseGrade(courseSchoolEX.getCourseGrade());
        //供应商信息
//        feignClassVO.setSupplierId(0L);
//        feignClassVO.setSupplierName("测试信息");
        //使用年级
        StringJoiner courseGrade = new StringJoiner(",");
        String[] courseGradeArr = courseSchoolEX.getCourseGrade().split(",");
        for (String gradeStr : courseGradeArr) {
            courseGrade.add(GradeEnum.getName(Integer.valueOf(gradeStr)));
        }
        if (courseSchoolEX.getGoodsFlag() == 1) {
            //查找教材教具信息
            AppGoodsVO goodMaterial = getGoodMaterial(courseClassId);
            feignClassVO.setMaterial(goodMaterial);
        }
        feignClassVO.setCourseGradeName(courseGrade.toString());
        return feignClassVO;
    }

    /**
     * 查找教具商品
     *
     * @param courseClassId 课程班级id
     */
    private AppGoodsVO getGoodMaterial(Long courseClassId) {
        QueryWrapper<CourseClassGoods> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(CourseClassGoods::getClassId, courseClassId);
        CourseClassGoods courseClassGoodsEX = courseClassGoodsService.getOne(queryWrapper);
        Optional.ofNullable(courseClassGoodsEX).orElseThrow(() -> new BusinessException(CourseExceptionEnum.GOODS_NOT_EXIST));
        AppGoodsVO material = new AppGoodsVO();
        material.setGoodsId(courseClassGoodsEX.getGoodsId());
        material.setGoodsCover(courseClassGoodsEX.getGoodsCover());
        material.setGoodsTitle(courseClassGoodsEX.getGoodsTitle());
        material.setGoodsName(courseClassGoodsEX.getGoodsName());
        material.setGoodsPrice(courseClassGoodsEX.getGoodsPrice());
        return material;
    }

    /**
     * 获取图片介绍
     *
     * @param courseId 课程id
     */
    private List<String> getIntroduceImg(Long courseId) {
        QueryWrapper<CourseImage> imageQueryWrapper = new QueryWrapper<>();
        imageQueryWrapper.lambda().eq(CourseImage::getCourseId, courseId);
        List<CourseImage> list = courseImageService.list(imageQueryWrapper);
        List<String> imageList = null;
        if (CollUtil.isNotEmpty(list)) {
            imageList = new ArrayList<>();
            for (CourseImage courseImage : list) {
                imageList.add(ImageUtil.addPrefix(courseImage.getIntroduceImg()));
            }
        }
        return imageList;
    }


    /**
     * 设置app按钮显示状态
     *
     * @param courseClassId    课程id
     * @param studentId        学生id
     * @param appCourseClassVO 返回信息
     */
    private void setBtnStatus(Long courseClassId, Long studentId, AppCourseClassVO appCourseClassVO) {
        //0-待报名
        if (ClassStatusEnum.TO_SIGN.getCode() == appCourseClassVO.getClassStatus()) {
            appCourseClassVO.setClassStatus(0);
        }
        //1-立即报名
        if (ClassStatusEnum.SIGN_IN.getCode() == appCourseClassVO.getClassStatus()) {
            boolean flag = feignOrderService.isSignUp(courseClassId, studentId);
            //2-已报名
            if (flag) {
                appCourseClassVO.setClassStatus(2);
            } else {
                //3-已报满 报名人数是否达到最大人数
                if (Objects.equals(appCourseClassVO.getStuNoMax(), appCourseClassVO.getSignUpNumber())) {
                    appCourseClassVO.setClassStatus(3);
                } else {
                    appCourseClassVO.setClassStatus(1);
                }
            }
        }
    }
}
